package com.unb.task;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.json.JSONException;

import android.os.AsyncTask;

import com.nutiteq.log.Log;

public abstract class RestTask extends AsyncTask<String, Void, List<String[]>> {

    @Override
    protected List<String[]> doInBackground(String... params) {
        HttpClient httpclient = null;
        HttpURLConnection urlConnection = null;

        try {
            URL url = new URL(params[0]);
            Log.debug("Parametros: " + params[0]);

            // // USANDO DefaultHttpClient
            // HttpParams httpParameters = new BasicHttpParams();
            // HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
            // HttpConnectionParams.setSoTimeout(httpParameters, 10000);
            // httpclient = new DefaultHttpClient(httpParameters);
            // HttpGet get = new HttpGet(params[0]);
            // Log.debug("Antes Header");
            // get.setHeader("Accept", "application/json");
            // Log.debug("Antes Response");
            // HttpResponse httpResponse = httpclient.execute(get);
            // Log.debug("Depois Response");
            // int receivedStatusCode =
            // httpResponse.getStatusLine().getStatusCode();
            // Log.debug("Depois GetStatusCode");
            // if (receivedStatusCode == HttpStatus.SC_OK) {
            // Log.debug("Antes inputStream");
            // InputStream inputStream = httpResponse.getEntity().getContent();
            // Log.debug("Depois inputStream");
            // String jsonData = toString(inputStream);
            // return handleJson(jsonData);
            // } else {
            // return null;
            // }

            // ------------------------------------------------------------------
            // USANDO HttpURLConnection

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(20000);
            urlConnection.setConnectTimeout(20000);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("GET");
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());

                String jsonData = toString(inputStream);
                return handleJson(jsonData);
            } else {
                return null;
            }

        } catch (IOException e) {
            Log.error("IOException: " + e.getMessage());
            return null;
        } catch (JSONException e) {
            Log.error("JSONException: " + e.getMessage());
            return null;
        }

    }

    /**
     * Converte o objeto <code>InputStream</code> recebido pela solicitaçăo
     * HTTP, e converte-o para um objeto <code>String</code> contendo JSON.
     * 
     * @param is
     *            Objeto <code>InputStream</code> de entrada.
     * @return Objeto <code>String</code> contendo o resultado JSON.
     */
    private String toString(InputStream is) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        Log.debug("Depois do BufferedReader");
        StringBuilder builder = new StringBuilder();
        Log.debug("Depois do Builder");
        for (String line = null; (line = reader.readLine()) != null;) {
            Log.debug("Dentro do For");
            builder.append(line).append("\n");

            if (isCancelled())
                break;
        }

        return builder.toString();

    }

    /**
     * Transforma a String JSON recebida em um array de Strings.
     * 
     * @param jsonData
     *            <code>String</code> contendo os dados JSON.
     * @return Resultado da conversão dos dados.
     * 
     * @throws JSONException
     *             Caso ocorra algum problema na conversão do JSON.
     */
    abstract protected List<String[]> handleJson(String jsonData) throws JSONException;
}
